package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConst;
import com.itheima.constant.RedisConst;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * 预约
 */
@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

	@Autowired
	JedisPool jedisPool;

	@Reference
	OrderService orderService;

	@RequestMapping("/submit")
	public Result submit(@RequestBody Map<String,String> map){

		log.debug(map.toString());


		String telephone = map.get("telephone");
		String validateCode = map.get("validateCode");


		String validateCodeInRedis = jedisPool.getResource().get(RedisConst.SENDTYPE_ORDER + "-" + telephone);
		//校验验证码
		if(!(validateCodeInRedis != null && validateCodeInRedis.equals(validateCode))){

			return new Result(false,MessageConst.ORDERSETTING_FAIL);

		}
		//指定预约方式:微信预约方式
		map.put("orderType", Order.ORDERTYPE_WEIXIN);

		Result result = orderService.addOrder(map);

		if(!result.isFlag()){

			return new Result(false,MessageConst.ORDERSETTING_FAIL);

		}


		return result;
	}

	@RequestMapping("findById")
	public Result findById(Integer id){
		log.debug("id="+id);

		Map<String,Object> map = orderService.findById(id);

		//把预约日期转换为字符串类型
		Date date = (Date) map.get("orderDate");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String orderDate = sdf.format(date);

		map.put("orderDate",orderDate);

		log.debug(map.toString());
		return new Result(true,MessageConst.QUERY_ORDER_SUCCESS,map);

	}


}
